<?php

namespace App\Http\Controllers;

use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Mockery\Exception;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    protected $messages = [
        'required' => ':attribute值不能为空！',
        'unique' => ':attribute已存在'
    ];
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $role = Role::orderBy('id')->paginate(8);
        $permisson = Permission::all();
        return view('role',[
            'role'=>$role,
            'permisson'=>$permisson
        ]);
    }

    public function rightManage(Request $request)
    {
        $ids = Input::get('ids');
        $id = Input::get('id');
        if($ids){
            $role = Role::findById($id)->syncPermissions($ids);
        }else{
            $role = Role::findById($id)->syncPermissions();
        }
    }

    public function edit($id)
    {
        $ids = DB::table('role_has_permissions')->select('permission_id')->where('role_id','=',$id)->get();
        return response()->json($ids);
    }


    public function store(Request $request)
    {
        $input = Input::all();
        if(Input::ajax()) {
            $this->validate($request, [
                'name' => 'bail|required|unique:roles|max:255',
            ], $this->messages);
            $role = Role::create(['name'=>$input['name'],'description'=>$input['description']]);
            return response()->json([
                'role' => $role
            ]);
        }
    }

    public function show($id)
    {
        //
        return __METHOD__;
    }

    public function update(Request $request, $id)
    {
        $input = $request->all();
        if(Input::ajax()){
            $this->validate($request, [
                'name' => 'bail|required|unique:roles,name,'.$id.'|max:255',
            ], $this->messages);
            $role = Role::findById($id);
            $role->name = $input['name'];
            $role->description = $input['description'];
            $role->save();
            return response()->json([
                'role' => $role
            ]);
        }
    }

    public function destroy($id)
    {
        $input = Input::get('id');
        if(Input::ajax()) {
            $role = Role::destroy($id);
            return response()->json([
                'id' => $id
            ]);
        }
    }
}
